package no.ntnu.fp.server;

import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import no.ntnu.fp.connection.Initializer;
import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.net.co.ConnectionImpl2;

public final class MainConnection {
	private final static int PORT_NUMBER = 33299;
	private final static Map<Employee, Connection> registeredEmployees = new Hashtable<Employee, Connection>();
	private final static Connection connection = new ConnectionImpl2(PORT_NUMBER);
	private final static Initializer initializer = new InitializerImpl();
	private final static ExecutorService executor = Executors.newCachedThreadPool();
	
	private static void startServer() {
		
		try {
			while (true) {
				Connection newConnection = connection.accept();
				executor.execute(new ReceiveWorker(newConnection));
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			executor.shutdownNow();
		}
	}
	
	public static synchronized void registerEmployee(Employee emp, Connection con) {
		registeredEmployees.put(emp, con);
	}
	
	public static synchronized void unregisterEmployee(Employee emp) {
		registeredEmployees.remove(emp);
	}
	
	public static synchronized Connection getConnection(Employee emp) {
		return registeredEmployees.get(emp);
	}
	
	public static void main(String[] args) {
		initializer.initialize();
		startServer();
	}
	
}
